import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface UserInfo {
  openid: string | null
  nickname: string
  avatar_url: string
  phone: string
}

export const useAuthStore = defineStore('auth', () => {
  // 登录状态
  const isLoggedIn = ref(false)
  const userInfo = ref<UserInfo | null>(null)
  const accessToken = ref<string | null>(null)
  const pendingRoute = ref<string | null>(null)

  // 检查登录状态
  const checkLoginStatus = () => {
    const token = localStorage.getItem('access_token')
    const user = localStorage.getItem('user_info')
    
    if (token && user) {
      accessToken.value = token
      userInfo.value = JSON.parse(user)
      isLoggedIn.value = true
      return true
    }
    return false
  }

  // 发送手机验证码
  const sendVerificationCode = async (phone: string): Promise<boolean> => {
    try {
      const response = await fetch('/api/auth/send-code', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ phone })
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.detail || '发送验证码失败')
      }

      const data = await response.json()
      return data.success
    } catch (error) {
      console.error('发送验证码错误:', error)
      throw error
    }
  }

  // 手机号登录
  const phoneLogin = async (phone: string, code: string): Promise<boolean> => {
    try {
      const response = await fetch('/api/auth/phone-login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ phone, code })
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.detail || '登录失败')
      }

      const data = await response.json()
      
      if (data.success) {
        // 保存登录信息
        accessToken.value = data.access_token
        userInfo.value = data.user_info
        isLoggedIn.value = true
        
        // 保存到本地存储
        localStorage.setItem('access_token', data.access_token)
        localStorage.setItem('user_info', JSON.stringify(data.user_info))
        
        return true
      } else {
        console.error('登录失败:', data.message)
        return false
      }
    } catch (error) {
      console.error('手机号登录错误:', error)
      throw error
    }
  }

  // 退出登录
  const logout = () => {
    isLoggedIn.value = false
    userInfo.value = null
    accessToken.value = null
    
    localStorage.removeItem('access_token')
    localStorage.removeItem('user_info')
  }

  // 获取用户信息
  const getUserInfo = () => {
    return userInfo.value
  }

  // 获取访问令牌
  const getAccessToken = () => {
    return accessToken.value
  }

  // 初始化时检查登录状态
  checkLoginStatus()

  return {
    isLoggedIn,
    userInfo,
    accessToken,
    pendingRoute,
    phoneLogin,
    sendVerificationCode,
    logout,
    getUserInfo,
    getAccessToken,
    checkLoginStatus
  }
}) 